import {
    createSlice,// 负责创建slice(片区，模块）
    configureStore// 创建仓库（store）
} from "@reduxjs/toolkit";
const goodsSlice = createSlice({
    name:"goods",
    initialState:{
        goodsList:[]
    },
    reducers:{
        addGoodsList(state,action){
            // 1
            // state.goodsList.push({
            //     id:state.goodsList.length,
            //     goodName:action.payload.goodsName,
            //     goodsPrice:action.payload.goodsPrice
            // })

            // 2
            // const {goodsName,goodsPrice} = action.payload;
            // state.goodsList.push({
            //     id:state.goodsList.length,
            //     goodsName,
            //     goodsPrice
            // })
            // console.log("reducer->addGoodsList")
            // 3
            state.goodsList.push({
                id:state.goodsList.length,
                ...action.payload
            })
        }
    }
});
const carSlice = createSlice({
    name:"car",
    initialState:{
        carList:[]
    },
    reducers:{
        joinCar(){
            console.log("joinCar")
        }
    }
});
const store = configureStore({
    reducer:{
        goods:goodsSlice.reducer,
        car:carSlice.reducer
    }
});
// 1- 读取仓库中的数据状态
// console.log(store.getState())

// 2- 操作（增加，删除，修改）仓库中的数据状态
// action:同步action(对象),异步action（函数），理解为命令。
// reducer:工人，执行命令。
// dispatch:发送命令。
// console.log(store.getState());
// store.dispatch({type:"goods/addGoodsList"});
// store.dispatch({type:"car/joinCar"});
// store.dispatch({type:"goods/addGoodsList",payload:{goodsName:"梨",goodsPrice:20}});
// store.dispatch({type:"goods/addGoodsList",payload:{goodsName:"苹果",goodsPrice:200}});
// 工厂函数
// function addGoodsListCreator(payload){
//     return {
//         type:"goods/addGoodsList",
//         payload
//     }
// }
// store.dispatch(addGoodsListCreator({goodsName:"梨",goodsPrice:20}))
// console.log(goodsSlice.actions.addGoodsList({goodsName:"梨",goodsPrice:20}));
const {addGoodsList} = goodsSlice.actions;
const unSubscribe = store.subscribe(function(){
    console.log("subscribe:store数据状态发生更改后执行",store.getState());
    unSubscribe();// 取消订阅
})
store.dispatch(addGoodsList({goodsName:"梨",goodsPrice:20}));
// const state = store.getState();
store.dispatch(addGoodsList({goodsName:"苹果",goodsPrice:20}));
// const state1 = store.getState();
// console.log(state===state1);


